#include <iostream>

#include "clientsocket.h"

ClientSocket::ClientSocket(QObject *parent) : QTcpSocket(parent)
{
    connect(this, SIGNAL(readyRead()), this, SLOT(readIncomingUsername()));
    connect(this, SIGNAL(disconnected()), this, SLOT(deleteLater()));

    nextBlockSize = 0;
}

void ClientSocket::readIncomingUsername()
{
    QDataStream in(this);
    in.setVersion(QDataStream::Qt_4_5);

    if (nextBlockSize == 0)
    {
        if(bytesAvailable() < sizeof(quint16))
            return;
        in >> nextBlockSize;
    }
    if (bytesAvailable() < nextBlockSize)
        return;

    QString username;

    in >> username;

    if (usernameExists(username))
    {
        generateReply("Login Successful");
    }
    else
    {
//        initializeUser(username);
        generateReply("Invalid Username");
    }

    QDataStream out(this);
    out << quint16(0xFFFF);

    close();
}

void ClientSocket::generateReply(const QString &reply)
{
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_5);
    out << quint16(0) << reply;
    out.device()->seek(0);
    out << quint16(block.size() - sizeof(quint16));

    write(block);
}

bool ClientSocket::usernameExists(const QString &username)
{
    QFile file(QDir::homePath() + "/Server/UserList.xml");
    file.open(QFile::ReadOnly | QFile::Text);
    QXmlStreamReader reader;
    reader.setDevice(&file);
    QStringList usernames;
    reader.readNext();
    while (!reader.atEnd())
    {
        if (reader.name() == "username")
        {
            usernames.append(reader.readElementText());
        }
        reader.readNext();
    }
    file.close();

    for (QStringList::iterator it = usernames.begin(); it != usernames.end(); ++it)
    {
        QString current = *it;
        qDebug() << current;
    }
    std::cout << usernames.size() << std::endl;
    if (usernames.contains(username))
    {
        return true;
    }
    else
    {
        return false;
    }
}

void ClientSocket::initializeUser(const QString &username)
{
    QFile fileRead(QDir::homePath() + "/Server/UserList.xml");
    fileRead.open(QFile::ReadOnly | QFile::Text);
    QXmlStreamReader reader;
    reader.setDevice(&fileRead);
    QStringList usernames;
    reader.readNext();
    while (!reader.atEnd())
    {
        if (reader.name() == "username")
        {
            usernames.append(reader.readElementText());
        }
        reader.readNext();
    }
    fileRead.close();

    QFile fileWrite(QDir::homePath() + "/Server/UserList.xml");

    fileWrite.open(QFile::WriteOnly | QFile::Text);
    QXmlStreamWriter xmlWriter(&fileWrite);
    xmlWriter.setAutoFormatting(true);
    xmlWriter.writeStartDocument();
    xmlWriter.writeStartElement("Userlist");
    if (usernames.size() == 0)
    {
        xmlWriter.writeTextElement("username", username);
    }
    else
    {
        for (QStringList::iterator it = usernames.begin(); it != usernames.end(); ++it)
        {
            QString current = *it;
            xmlWriter.writeTextElement("username", current);
        }
        xmlWriter.writeTextElement("username", username);
    }
    xmlWriter.writeEndDocument();
    fileWrite.close();

    QDir media;
    media.mkdir(QDir::homePath() + "/Server/Media/" + username);

    QFile xmlFile(QDir::homePath() + "/Server/Logs/" + username + ".xml");
    xmlFile.open(QFile::WriteOnly | QFile::Text);
    xmlFile.close();
}
